package com.cmas.platform.service.impl;

import java.util.List;

import com.aidex.common.annotation.DataSource;
import com.aidex.common.constant.Constants;
import com.aidex.common.enums.DataSourceType;
import com.aidex.common.exception.CustomException;
import com.alibaba.fastjson2.JSONObject;
import com.cmas.platform.domain.Comment;
import com.cmas.platform.domain.Post;
import com.cmas.platform.domain.UserLike;
import com.cmas.platform.domain.em.ApproveStatusEnum;
import com.cmas.platform.mapper.CommentMapper;
import com.cmas.platform.mapper.PostMapper;
import com.cmas.platform.mapper.UserLikeMapper;
import com.cmas.platform.vo.UserInfoRecordVo;
import com.cmas.platform.vo.UserRecordVo;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.platform.mapper.UserRecordMapper;
import com.cmas.platform.domain.UserRecord;
import com.cmas.platform.service.UserRecordService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户记录表Service业务层处理
 *
 * @author su
 * @email 1218819874@qq.com
 * @date 2023-04-28
 */
@Service
public class UserRecordServiceImpl extends ServiceImpl<UserRecordMapper, UserRecord> implements UserRecordService {

    private static final Logger log = LoggerFactory.getLogger(UserRecordServiceImpl.class);

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserLikeMapper userLikeMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    /**
     * 查询用户记录表列表
     *
     * @param userRecord 用户记录表
     * @return 用户记录表
     */
    @Override
    public List<UserRecord> selectUserRecordList(UserRecord userRecord) {
        QueryWrapper<UserRecord> queryWrapper = setQueryWrapper(userRecord);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<UserRecordVo> selectUserRecordVoList(UserRecord userRecord) {
        QueryWrapper<UserRecord> queryWrapper = setQueryWrapper(userRecord);
        return baseMapper.selectUserRecordList(queryWrapper);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = Constants.RECORD_QUEUE, durable = "true"),
            exchange = @Exchange(name = Constants.RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = Constants.RECORD_QUEUE_ROUTING_KEY))
    @DataSource(value = DataSourceType.SLAVE)
    public void statisticsRecordByRabbitmq(String msg) {
        try {
            JSONObject message = JSONObject.parse(msg);
            String userId = message.getString("userId");
            if (StringUtils.isNotEmpty(userId)) {
                UserRecord userRecord = baseMapper.selectOne(new QueryWrapper<UserRecord>()
                        .lambda().eq(UserRecord::getUserId, userId));
                if (userRecord == null) {
                    userRecord = new UserRecord();
                    userRecord.setUserId(userId);
                }
                //重置数量
                resetUserRecordNumber(userRecord);
                //帖子统计
                statisticsPost(userRecord);
                //评论统计
                statisticsComment(userRecord);
                //点赞统计
                userRecord.setLikeNumber(userLikeMapper.selectCount(new QueryWrapper<UserLike>()
                        .lambda().eq(UserLike::getUserId, userId).eq(UserLike::getIsLike,"1")));
                //插入修改判断
                if (StringUtils.isNotEmpty(userRecord.getId())) {
                    baseMapper.updateById(userRecord);
                } else {
                    baseMapper.insert(userRecord);
                }
            }
        } catch (Exception e) {
            throw new CustomException("消息接受失败!");
        }

    }

    private void resetUserRecordNumber(UserRecord userRecord){
        userRecord.setPostNumber(0L);
        userRecord.setPublishPostNumber(0);
        userRecord.setCommentNumber(0);
        userRecord.setPublishCommentNumber(0);
        userRecord.setLikeNumber(0);
        userRecord.setBeLikeNumber(0);
        userRecord.setBeCollectNumber(0);
        userRecord.setBeCommentNumber(0);
    }

    private void statisticsComment(UserRecord userRecord) {
        List<Comment> commentList = commentMapper.selectList(new QueryWrapper<Comment>()
                .lambda().eq(Comment::getUserId, userRecord.getUserId())
                .in(Comment::getStatus, ApproveStatusEnum.AUTOMATIC_PASS.getValue()
                        ,ApproveStatusEnum.ARTIFICIAL_PASS.getValue()));
        for (Comment comment : commentList) {
            userRecord.setBeLikeNumber(comment.getLikeNumber() + userRecord.getBeLikeNumber());
        }
        userRecord.setPublishCommentNumber(commentList.size());
    }


    private void statisticsPost(UserRecord userRecord) {
        List<Post> postList = postMapper.selectList(new QueryWrapper<Post>()
                .lambda().eq(Post::getUserId, userRecord.getUserId())
                .in(Post::getStatus, ApproveStatusEnum.AUTOMATIC_PASS.getValue()
                        ,ApproveStatusEnum.ARTIFICIAL_PASS.getValue()));
        userRecord.setPublishPostNumber(postList.size());
        for (Post post : postList) {
            userRecord.setBeCollectNumber(post.getCollectNumber() + userRecord.getCollectNumber());
            userRecord.setPostNumber(post.getViewNumber() + userRecord.getPostNumber());
            userRecord.setBeLikeNumber(post.getLikeNumber() + userRecord.getBeLikeNumber());
        }
    }


    /**
     * 批量删除用户记录表
     *
     * @param ids 需要删除的用户记录表ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteUserRecordByIds(String[] ids) {
        return baseMapper.deleteUserRecordByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public UserInfoRecordVo getUserInfoRecord(String userId) {
        sendMessage(Constants.RECORD_EXCHANGE, Constants.RECORD_QUEUE_ROUTING_KEY, userId);
        return baseMapper.selectUserInfoRecord(userId);
    }

    public void sendMessage(String exchange, String key, String userId) {
        JSONObject data = new JSONObject();
        data.put("userId", userId);
        rabbitTemplate.convertAndSend(exchange, key, data.toString());
    }

    public QueryWrapper<UserRecord> setQueryWrapper(UserRecord userRecord) {
        QueryWrapper<UserRecord> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(userRecord.getUserId())) {
            queryWrapper.eq("cmas.user_record.user_id", userRecord.getUserId());
        }
        if (StringUtils.isNotEmpty(userRecord.getRegionId())) {
            queryWrapper.eq("cmas.user_record.region_id", userRecord.getRegionId());
        }
        if (userRecord.getPublishPostNumber() != null) {
            queryWrapper.lambda().gt(UserRecord::getPublishPostNumber, userRecord.getPublishPostNumber());
        }
        if (userRecord.getPublishCommentNumber() != null) {
            queryWrapper.lambda().gt(UserRecord::getPublishCommentNumber, userRecord.getPublishCommentNumber());
        }
        return queryWrapper;
    }


}
